<template>
  <span
    ref="iconContainer"
    v-if="svgs[iconName]"
    :class="typeClass"
    :style="mergedStyle"
    v-html="svgs[iconName]"
    @click="clickFn"
  ></span>
  <span v-else></span>
</template>

<script setup lang="ts">
import { computed, defineProps, onMounted, ref } from "vue";
import styles from "./SVGIcon.module.less";
import classNames from "classnames";

interface IconProps {
  iconName: string;
  type?: "default" | "hover";
  className?: string;
  style?: Record<string, any>;
  onClick?: () => void;
  size?: string | number;
  disable?: boolean;
}

const props = defineProps<IconProps>();

const svgs = ref<Record<string, string>>({});
const importSvgs = async () => {
  try {
    // 动态导入svg文件
    // @ts-ignore
    const svgContext = require.context("../../assets/icons", false, /\.svg$/);

    // 获取所有svg文件的路径
    const svgPaths = svgContext.keys();

    // 载入这些路径指示的SVG模块
    svgPaths.forEach((path: string) => {
      const name = path.replace(/.\/|.svg$/g, "");
      svgs.value[name] = svgContext(path).default;
    });
  } catch (error) {
    console.error("Error importing SVGs:", error);
  }
};
importSvgs();

const iconContainer = ref<HTMLElement | null>(null);
const updateSvgAttributes = () => {
  if (iconContainer.value) {
    const svgElement = iconContainer.value.querySelector("svg");
    if (svgElement) {
      svgElement.removeAttribute("width");
      svgElement.removeAttribute("height");
    }
  }
};

onMounted(() => {
  updateSvgAttributes();
});

const typeClass = computed(() => {
  return classNames({
    [styles.icon]: true,
    [styles.icon_default]: props.type === "default",
    [styles.icon_hover]: props.type === "hover",
    [styles.disable]: props.disable,
  });
});

const svgStyle = computed(() => ({
  width: props.size + "px" || "16px",
  height: props.size + "px" || "16px",
  cursor: props.disable ? "not-allowed" : props.onClick ? "pointer" : "default",
}));

const mergedStyle = computed(() => ({
  ...svgStyle.value,
  ...props.style,
}));

const clickFn = () => {
  if (!props.disable) {
    props.onClick && props.onClick();
  }
};
</script>

<style scoped lang="less">
@import "./SVGIcon.module.less";
</style>
